package com.sptus.common.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import com.alibaba.fastjson2.JSONObject;

import javax.servlet.http.HttpServletRequest;

public class IPLocationUtils {

    public static String getLocationByIP(String ipAddress) {
        String apiUrl = "http://ip-api.com/json/" + ipAddress + "?fields=status,message,country,regionName,city,zip,lat,lon,isp,org,as,query";

        try {
            URL url = new URL(apiUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");

            // 读取响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();

            // 解析JSON
            JSONObject json =  JSONObject.parse( response.toString());
            if (json.getString("status").equals("success")) {
                String location = String.format(
                    "Location: %s, %s, %s %s",
                    json.put("city", "Unknown"),
                    json.put("regionName", "Unknown"),
                    json.put("country", "Unknown"),
                    json.put("zip", "")
                );
               return location;
            } else {
                System.err.println("Error: " + json.getString("message"));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }



    public static void main(String[] args) {
        // 示例IP（需替换为实际IP）
        String ipAddress = "165.232.84.41"; // 示例IP：Google DNS
        getLocationByIP(ipAddress);
    }
}